package com.Arsanesia.TempleRush.Controllers;

import com.Arsanesia.TempleRush.Enumeration.TempleRushSound;
import com.Arsanesia.TempleRush.Helpers.LRUCache;
import com.Arsanesia.TempleRush.Helpers.LRUCache.CacheEntryRemovedListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Disposable;

public class SoundManager implements StreamManager, Disposable, 
CacheEntryRemovedListener<TempleRushSound,Sound>{
	
	private boolean enabled = true;
	private final LRUCache<TempleRushSound, Sound> soundCache;
	private TempleRushSound sound;
	
	public SoundManager(){
		soundCache = new LRUCache<TempleRushSound, Sound>(12);
		soundCache.setEntryRemovedListener(this);
	}
	@Override
	public <Stream> void play(Stream stream) {
		  // check if the sound is enabled
        if( ! enabled ) return;
        if(stream.getClass() == TempleRushSound.class){
        sound = (TempleRushSound) stream;
        	// try and get the sound from the cache
	        Sound soundToPlay = soundCache.get( sound ); 
			if( soundToPlay == null ) {
		            FileHandle soundFile = Gdx.files.internal( sound.getFileName() );
		            soundToPlay = Gdx.audio.newSound( soundFile );
		            soundCache.add( sound, soundToPlay );
		     }
		     soundToPlay.play();
        }
		
	}

	@Override
	public void stop() {
		for( Sound sound : soundCache.retrieveAll() ) {
            sound.stop();
        }
		
	}

	@Override
	public void setEnabled(boolean _enabled) {
		enabled = _enabled;
		if(!enabled) stop();
		
	}

	@Override
	public boolean isEnabled() {
		return enabled;
	}

	@Override
	public void toggleEnable() {
		setEnabled(!enabled);
	}

	@Override
	public void dispose() {
		for( Sound sound : soundCache.retrieveAll() ) {
            sound.stop();
            sound.dispose();
        }
	}
	@Override
	public void notifyEntryRemoved(TempleRushSound key, Sound value) {
		value.dispose();
	}

}
